import QtQuick 2.12
import QtQuick.Controls 2.12
import QtLocation 5.12
import QtPositioning 5.12

/**
 * @brief 高德地图瓦片查看器
 * 使用YCLocationProvider插件，支持高德地图瓦片加载
 * 参考yclocation-master项目实现
 */
Item {
    id: tiledMapViewer
    
    // ==================== 属性定义 ====================
    
    // 地图中心和缩放
    property real centerLon: 109.24015
    property real centerLat: 23.724696
    property int zoomLevel: 16
    
    // 状态
    property bool isMapReady: false
    property bool pathEditMode: false
    property bool fieldPlanMode: false  // 农田规划模式
    property bool fieldPlanSaved: false  // 农田规划是否已保存
    
    // 样式配置
    property color pathLineColor: "#2196f3"
    property int pathLineWidth: 4
    property color pathPointColor: "#f44336"
    property color routeLineColor: "#4caf50"
    property color robotPositionColor: "#ff9800"
    property color fieldAreaColor: "#ff9800"  // 农田区域颜色（半透明橙色）
    property color fieldBorderColor: "#f57c00"  // 农田边界颜色
    property color fieldBorderColorSaved: "#4caf50"  // 已保存农田边界颜色（绿色）
    
    // 模型别名（供外部访问）
    property alias pathPointsModel: pathPointsModel
    property alias robotPositionsModel: robotPositionsModel
    property alias routePathModel: routePathModel
    property alias fieldPointsModel: fieldPointsModel
    
    // ==================== 信号定义 ====================
    
    signal mapReady()
    signal locationChanged(real lon, real lat)
    signal mapClicked(real lon, real lat)
    signal pathPointAdded(real lon, real lat, int index)
    signal pathPointRemoved(int index)
    signal pathChanged()
    
    // ==================== 数据模型 ====================
    
    ListModel {
        id: pathPointsModel
    }
    
    ListModel {
        id: robotPositionsModel
    }
    
    ListModel {
        id: routePathModel
    }
    
    ListModel {
        id: fieldPointsModel  // 农田规划点
    }
    
    // ==================== 地图插件配置 ====================
    
    Plugin {
        id: mapPlugin
        name: "YCLocationProvider"  // 自定义插件名称
        
        // 插件会自动加载高德地图瓦片
        // URL格式由GaodeMapProvider.cpp定义
    }
    
    // ==================== 地图组件 ====================
    
    Map {
        id: map
        anchors.fill: parent
        plugin: mapPlugin
        
        // 手势配置
        gesture.acceptedGestures: MapGestureArea.PinchGesture | MapGestureArea.PanGesture | MapGestureArea.FlickGesture
        gesture.flickDeceleration: 3000
        
        // 缩放级别限制
        minimumZoomLevel: 3
        maximumZoomLevel: 20
        zoomLevel: tiledMapViewer.zoomLevel
        
        // 地图中心
        center: QtPositioning.coordinate(centerLat, centerLon)
        
        Component.onCompleted: {
            console.log("======================================")
            console.log("高德地图初始化完成")
            console.log("支持的地图类型数量:", supportedMapTypes.length)
            
            if (supportedMapTypes.length > 0) {
                activeMapType = supportedMapTypes[0]
                console.log("当前地图类型:", activeMapType.name)
                console.log("地图插件:", plugin.name)
            } else {
                console.warn("警告：没有可用的地图类型！")
            }
            
            console.log("地图中心:", centerLat, centerLon)
            console.log("缩放级别:", zoomLevel)
            console.log("======================================")
            
            // 延迟发送mapReady信号，确保组件完全初始化
            Qt.callLater(function() {
                isMapReady = true
                tiledMapViewer.mapReady()
            })
        }
        
        onCenterChanged: {
            centerLon = center.longitude
            centerLat = center.latitude
            locationChanged(centerLon, centerLat)
        }
        
        onZoomLevelChanged: {
            tiledMapViewer.zoomLevel = Math.round(zoomLevel)
        }
        
        // ==================== 地图点击处理 ====================
        
        MouseArea {
            anchors.fill: parent
            acceptedButtons: Qt.LeftButton | Qt.RightButton
            
            onClicked: {
                var coordinate = map.toCoordinate(Qt.point(mouse.x, mouse.y))
                console.log("地图点击坐标:", coordinate.latitude.toFixed(6), coordinate.longitude.toFixed(6))
                
                // 农田规划模式处理
                if (fieldPlanMode && mouse.button === Qt.LeftButton) {
                    addFieldPoint(coordinate.longitude, coordinate.latitude)
                }
                // 路径编辑模式处理
                else if (pathEditMode) {
                    if (mouse.button === Qt.LeftButton) {
                        // 左键添加路径点
                        addPathPoint(coordinate.longitude, coordinate.latitude)
                    } else if (mouse.button === Qt.RightButton) {
                        // 右键删除最近的路径点
                        removeNearestPathPoint(coordinate.longitude, coordinate.latitude)
                    }
                } else {
                    // 普通模式下触发地图点击信号
                    mapClicked(coordinate.longitude, coordinate.latitude)
                }
            }
        }
        
        // ==================== Canvas绘制路径 ====================
        
        Canvas {
            id: routeCanvas
            anchors.fill: parent
            renderTarget: Canvas.FramebufferObject  // 使用FBO提高性能
            
            // Canvas尺寸变化时重绘
            onWidthChanged: requestPaint()
            onHeightChanged: requestPaint()
            
            onPaint: {
                var ctx = getContext("2d")
                ctx.clearRect(0, 0, width, height)
                
                // 1. 绘制规划路线（绿色实线）
                if (routePathModel.count > 1) {
                    ctx.strokeStyle = routeLineColor
                    ctx.lineWidth = pathLineWidth
                    ctx.beginPath()
                    
                    for (var i = 0; i < routePathModel.count; i++) {
                        var routePoint = routePathModel.get(i)
                        var screenPoint = map.fromCoordinate(QtPositioning.coordinate(routePoint.lat, routePoint.lon))
                        
                        if (i === 0) {
                            ctx.moveTo(screenPoint.x, screenPoint.y)
                        } else {
                            ctx.lineTo(screenPoint.x, screenPoint.y)
                        }
                    }
                    ctx.stroke()
                }
                
                // 2. 绘制用户路径点连线（蓝色实线）
                if (pathPointsModel.count > 1) {
                    ctx.strokeStyle = pathLineColor
                    ctx.lineWidth = 3
                    ctx.beginPath()
                    
                    for (var j = 0; j < pathPointsModel.count; j++) {
                        var pathPoint = pathPointsModel.get(j)
                        var pathScreenPoint = map.fromCoordinate(QtPositioning.coordinate(pathPoint.lat, pathPoint.lon))
                        
                        if (j === 0) {
                            ctx.moveTo(pathScreenPoint.x, pathScreenPoint.y)
                        } else {
                            ctx.lineTo(pathScreenPoint.x, pathScreenPoint.y)
                        }
                    }
                    ctx.stroke()
                }
                
                // 3. 绘制路径点（红色圆点带序号）- 优化序号显示
                for (var k = 0; k < pathPointsModel.count; k++) {
                    var point = pathPointsModel.get(k)
                    var pointScreen = map.fromCoordinate(QtPositioning.coordinate(point.lat, point.lon))
                    var pointNumber = (k + 1).toString()  // 序号（从1开始）
                    
                    // 绘制外圈（白色边框）
                    ctx.strokeStyle = "white"
                    ctx.lineWidth = 3
                    ctx.fillStyle = pathPointColor
                    ctx.beginPath()
                    ctx.arc(pointScreen.x, pointScreen.y, 12, 0, 2 * Math.PI)  // 增大半径到12
                    ctx.fill()
                    ctx.stroke()
                    
                    // 绘制序号背景（半透明黑色圆，提高可读性）
                    ctx.fillStyle = "rgba(0, 0, 0, 0.6)"
                    ctx.beginPath()
                    ctx.arc(pointScreen.x, pointScreen.y, 8, 0, 2 * Math.PI)
                    ctx.fill()
                    
                    // 绘制序号文字（白色，加粗，更大字体）
                    ctx.fillStyle = "white"
                    ctx.font = "bold 14px Arial"  // 增大字体到14px
                    ctx.textAlign = "center"
                    ctx.textBaseline = "middle"
                    ctx.fillText(pointNumber, pointScreen.x, pointScreen.y)
                }
                
                // 4. 绘制农田规划区域（多边形和标点）
                if (fieldPointsModel.count > 0) {
                    // 绘制填充多边形（只在未保存且点数>=3时显示）
                    if (!fieldPlanSaved && fieldPointsModel.count >= 3) {
                        ctx.fillStyle = Qt.rgba(fieldAreaColor.r, fieldAreaColor.g, fieldAreaColor.b, 0.3)
                        ctx.beginPath()
                        
                        for (var f = 0; f < fieldPointsModel.count; f++) {
                            var fieldPoint = fieldPointsModel.get(f)
                            var fieldScreen = map.fromCoordinate(QtPositioning.coordinate(fieldPoint.lat, fieldPoint.lon))
                            
                            if (f === 0) {
                                ctx.moveTo(fieldScreen.x, fieldScreen.y)
                            } else {
                                ctx.lineTo(fieldScreen.x, fieldScreen.y)
                            }
                        }
                        ctx.closePath()
                        ctx.fill()
                    }
                    
                    // 绘制边界线（仅在点数>=2时显示连线）
                    if (fieldPointsModel.count >= 2) {
                        ctx.strokeStyle = fieldPlanSaved ? fieldBorderColorSaved : fieldBorderColor
                        ctx.lineWidth = fieldPlanSaved ? 2 : 3
                        ctx.setLineDash(fieldPlanSaved ? [5, 5] : [])  // 已保存时使用虚线
                        ctx.beginPath()
                        
                        for (var f2 = 0; f2 < fieldPointsModel.count; f2++) {
                            var fieldPoint2 = fieldPointsModel.get(f2)
                            var fieldScreen2 = map.fromCoordinate(QtPositioning.coordinate(fieldPoint2.lat, fieldPoint2.lon))
                            
                            if (f2 === 0) {
                                ctx.moveTo(fieldScreen2.x, fieldScreen2.y)
                            } else {
                                ctx.lineTo(fieldScreen2.x, fieldScreen2.y)
                            }
                        }
                        
                        // 如果有3个或更多点，闭合多边形
                        if (fieldPointsModel.count >= 3) {
                            ctx.closePath()
                        }
                        ctx.stroke()
                        ctx.setLineDash([])  // 重置虚线模式
                    }
                    
                    // 绘制农田规划点（增强显示）- 任何数量的点都显示
                    for (var f3 = 0; f3 < fieldPointsModel.count; f3++) {
                        var fieldPoint3 = fieldPointsModel.get(f3)
                        var fieldScreen3 = map.fromCoordinate(QtPositioning.coordinate(fieldPoint3.lat, fieldPoint3.lon))
                        
                        // 绘制外圈
                        ctx.fillStyle = fieldPlanSaved ? fieldBorderColorSaved : fieldBorderColor
                        ctx.strokeStyle = "white"
                        ctx.lineWidth = 3
                        ctx.beginPath()
                        ctx.arc(fieldScreen3.x, fieldScreen3.y, 12, 0, 2 * Math.PI)
                        ctx.fill()
                        ctx.stroke()
                        
                        // 绘制内圈
                        ctx.fillStyle = "white"
                        ctx.beginPath()
                        ctx.arc(fieldScreen3.x, fieldScreen3.y, 8, 0, 2 * Math.PI)
                        ctx.fill()
                        
                        // 绘制序号
                        ctx.fillStyle = fieldPlanSaved ? fieldBorderColorSaved : fieldBorderColor
                        ctx.font = "bold 12px Arial"
                        ctx.textAlign = "center"
                        ctx.textBaseline = "middle"
                        ctx.fillText((f3 + 1).toString(), fieldScreen3.x, fieldScreen3.y)
                    }
                }
                
                // 5. 绘制机器人位置（橙色圆点）
                for (var m = 0; m < robotPositionsModel.count; m++) {
                    var robot = robotPositionsModel.get(m)
                    var robotScreen = map.fromCoordinate(QtPositioning.coordinate(robot.lat, robot.lon))
                    
                    // 绘制机器人位置点
                    ctx.fillStyle = robotPositionColor
                    ctx.strokeStyle = "white"
                    ctx.lineWidth = 2
                    ctx.beginPath()
                    ctx.arc(robotScreen.x, robotScreen.y, 8, 0, 2 * Math.PI)
                    ctx.fill()
                    ctx.stroke()
                    
                    // 绘制机器人ID
                    if (robot.id) {
                        ctx.fillStyle = "white"
                        ctx.font = "bold 10px Arial"
                        ctx.textAlign = "center"
                        ctx.fillText(robot.id, robotScreen.x, robotScreen.y)
                    }
                }
            }
            
            // 地图变化时自动重绘
            Connections {
                target: map
                onCenterChanged: routeCanvas.requestPaint()
                onZoomLevelChanged: routeCanvas.requestPaint()
                onWidthChanged: routeCanvas.requestPaint()
                onHeightChanged: routeCanvas.requestPaint()
                onVisibleRegionChanged: routeCanvas.requestPaint()
            }
            
            // 模型变化时重绘
            Connections {
                target: pathPointsModel
                onCountChanged: routeCanvas.requestPaint()
            }
            
            Connections {
                target: routePathModel
                onCountChanged: routeCanvas.requestPaint()
            }
            
            Connections {
                target: robotPositionsModel
                onCountChanged: routeCanvas.requestPaint()
            }
            
            Connections {
                target: fieldPointsModel
                onCountChanged: routeCanvas.requestPaint()
            }
            
            // 监听fieldPlanSaved属性变化
            Connections {
                target: tiledMapViewer
                onFieldPlanSavedChanged: routeCanvas.requestPaint()
            }
        }
    }
    
    // ==================== JavaScript函数 ====================
    
    // 设置规划路线
    function setRoutePath(coordinates) {
        routePathModel.clear()
        for (var i = 0; i < coordinates.length; i++) {
            var coord = coordinates[i]
            routePathModel.append({
                lon: coord.lng || coord.lon,
                lat: coord.lat
            })
        }
        routeCanvas.requestPaint()
        console.log("路线绘制完成，共", routePathModel.count, "个点")
    }
    
    function clearRoute() {
        routePathModel.clear()
        routeCanvas.requestPaint()
        console.log("清除规划路线")
    }
    
    // 机器人位置管理
    function updateRobotPosition(id, lon, lat, status) {
        // 查找是否已存在该机器人
        for (var i = 0; i < robotPositionsModel.count; i++) {
            var robot = robotPositionsModel.get(i)
            if (robot.id === id) {
                robotPositionsModel.set(i, {id: id, lon: lon, lat: lat, status: status || "在线"})
                routeCanvas.requestPaint()
                return
            }
        }
        
        // 不存在则添加
        robotPositionsModel.append({id: id, lon: lon, lat: lat, status: status || "在线"})
        routeCanvas.requestPaint()
    }
    
    function clearRobotPositions() {
        robotPositionsModel.clear()
        routeCanvas.requestPaint()
    }
    
    // 地图操作
    function zoomIn() {
        if (map.zoomLevel < map.maximumZoomLevel) {
            map.zoomLevel += 1
        }
    }
    
    function zoomOut() {
        if (map.zoomLevel > map.minimumZoomLevel) {
            map.zoomLevel -= 1
        }
    }
    
    function setMapCenter(lon, lat) {
        map.center = QtPositioning.coordinate(lat, lon)
    }
    
    function setZoomLevel(level) {
        map.zoomLevel = level
    }
    
    function resetView() {
        map.center = QtPositioning.coordinate(23.724696, 109.24015)
        map.zoomLevel = 16
    }
    
    // 路径编辑模式
    function setPathEditMode(enabled) {
        pathEditMode = enabled
        console.log("路径编辑模式:", enabled ? "开启" : "关闭")
    }
    
    function togglePathEditMode() {
        pathEditMode = !pathEditMode
        console.log("路径编辑模式:", pathEditMode ? "启用" : "禁用")
    }
    
    // 清除路径
    function clearPath() {
        console.log("清除所有路径点")
        pathPointsModel.clear()
        routePathModel.clear()
        routeCanvas.requestPaint()
        pathChanged()
    }
    
    // 设置路径点
    function setPathPoints(points) {
        pathPointsModel.clear()
        for (var i = 0; i < points.length; i++) {
            pathPointsModel.append({
                lon: points[i].lon,
                lat: points[i].lat
            })
        }
        routeCanvas.requestPaint()
        pathChanged()
    }
    
    // 添加路径点
    function addPathPoint(lon, lat) {
        pathPointsModel.append({lon: lon, lat: lat})
        console.log("添加路径点:", lon.toFixed(6), lat.toFixed(6))
        routeCanvas.requestPaint()
        pathChanged()
    }
    
    // 删除最近的路径点
    function removeNearestPathPoint(lon, lat) {
        if (pathPointsModel.count === 0) {
            console.log("没有路径点可删除")
            return
        }
        
        var minDistance = Number.MAX_VALUE
        var nearestIndex = -1
        
        // 计算点到所有路径点的距离，找到最近的
        for (var i = 0; i < pathPointsModel.count; i++) {
            var point = pathPointsModel.get(i)
            var dx = point.lon - lon
            var dy = point.lat - lat
            var distance = Math.sqrt(dx * dx + dy * dy)
            
            if (distance < minDistance) {
                minDistance = distance
                nearestIndex = i
            }
        }
        
        // 阈值：如果距离小于0.001度（约100米），则删除
        if (minDistance < 0.001 && nearestIndex >= 0) {
            var removedPoint = pathPointsModel.get(nearestIndex)
            pathPointsModel.remove(nearestIndex)
            console.log("删除路径点:", removedPoint.lon.toFixed(6), removedPoint.lat.toFixed(6))
            routeCanvas.requestPaint()
            pathChanged()
        } else {
            console.log("未找到可删除的路径点（距离过远）")
        }
    }
    
    // 计算路径长度
    function calculatePathLength() {
        if (pathPointsModel.count < 2) return 0
        
        var totalLength = 0
        for (var i = 0; i < pathPointsModel.count - 1; i++) {
            var p1 = pathPointsModel.get(i)
            var p2 = pathPointsModel.get(i + 1)
            
            // 使用Haversine公式计算距离
            var R = 63710 // 地球半径（米）
            var dLat = (p2.lat - p1.lat) * Math.PI / 180
            var dLon = (p2.lon - p1.lon) * Math.PI / 180
            var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                    Math.cos(p1.lat * Math.PI / 180) * Math.cos(p2.lat * Math.PI / 180) *
                    Math.sin(dLon/2) * Math.sin(dLon/2)
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
            totalLength += R * c
        }
        return totalLength
    }
    
    // 设置路线路径（从RouteService）
    function setRoutePathFromService(path) {
        routePathModel.clear()
        for (var i = 0; i < path.length; i++) {
            routePathModel.append({
                lon: path[i].lon,
                lat: path[i].lat
            })
        }
        routeCanvas.requestPaint()
    }
    
    // ==================== 农田规划功能 ====================
    
    // 添加农田规划点
    function addFieldPoint(lon, lat) {
        fieldPointsModel.append({lon: lon, lat: lat})
        fieldPlanSaved = false  // 添加点时标记为未保存
        console.log("添加农田规划点:", lon.toFixed(6), lat.toFixed(6), "总数:", fieldPointsModel.count)
        routeCanvas.requestPaint()
    }
    
    // 清除农田规划
    function clearFieldPlan() {
        fieldPointsModel.clear()
        fieldPlanMode = false
        fieldPlanSaved = false
        console.log("清除农田规划")
        routeCanvas.requestPaint()
    }
    
    // 切换农田规划模式
    function toggleFieldPlanMode() {
        fieldPlanMode = !fieldPlanMode
        if (!fieldPlanMode) {
            // 退出模式时不清除点，只切换模式
            console.log("退出农田规划模式")
        } else {
            console.log("进入农田规划模式")
            // 进入规划模式时，如果有未保存的农田，标记为未保存状态
            if (fieldPointsModel.count >= 3) {
                fieldPlanSaved = false
            }
        }
    }
    
    // 标记农田为已保存状态
    function markFieldPlanAsSaved() {
        fieldPlanSaved = true
        console.log("农田规划已标记为已保存")
        routeCanvas.requestPaint()
    }
    
    // 标记农田为未保存状态
    function markFieldPlanAsUnsaved() {
        fieldPlanSaved = false
        console.log("农田规划已标记为未保存")
        routeCanvas.requestPaint()
    }
    
    // 计算农田面积（亩）
    function calculateFieldArea() {
        if (fieldPointsModel.count < 3) {
            return 0
        }
        
        // 使用球面多边形面积计算公式
        var R = 63710 // 地球半径（米）
        var area = 0
        
        for (var i = 0; i < fieldPointsModel.count; i++) {
            var p1 = fieldPointsModel.get(i)
            var p2 = fieldPointsModel.get((i + 1) % fieldPointsModel.count)
            
            area += (p2.lon - p1.lon) * (2 + Math.sin(p1.lat * Math.PI / 180) + Math.sin(p2.lat * Math.PI / 180))
        }
        
        area = Math.abs(area * R * R / 2)
        
        // 转换为亩（1平方米 = 0.0015亩）
        var mu = area * 0.0015
        
        return mu
    }
    
    // 获取农田规划信息
    function getFieldPlanInfo() {
        return {
            pointCount: fieldPointsModel.count,
            areaMu: calculateFieldArea(),
            isComplete: fieldPointsModel.count >= 3
        }
    }
    
    // 加载农田规划
    function loadFieldPlan(points) {
        if (!points || points.length < 3) {
            console.warn("无法加载：农田点数不足3个")
            return false
        }
        
        fieldPointsModel.clear()
        for (var i = 0; i < points.length; i++) {
            fieldPointsModel.append({
                lon: points[i].lon,
                lat: points[i].lat
            })
        }
        
        // 加载的农田默认为已保存状态
        fieldPlanSaved = true
        
        console.log("加载农田规划成功，点数:", fieldPointsModel.count)
        routeCanvas.requestPaint()
        return true
    }
    
    // 获取农田规划点数据
    function getFieldPlanData() {
        var points = []
        for (var i = 0; i < fieldPointsModel.count; i++) {
            var point = fieldPointsModel.get(i)
            points.push({
                lon: point.lon,
                lat: point.lat
            })
        }
        return points
    }
}
